/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Nhattruong
 */
public class SocketReceiver extends Thread {

    Socket _socket;
    MessageHandlerInterface messageHandlerInterface;
    BufferedReader _bf;
    private boolean _stopListen = false;

    public SocketReceiver(Socket sk, MessageHandlerInterface mh) throws IOException {
        _socket = sk;
        _bf = new BufferedReader(new InputStreamReader(sk.getInputStream()));
        messageHandlerInterface = mh;
    }

    public void stopListen() throws IOException {
        this._stopListen = true;
        _socket.close();
    }

    @Override
    public void run() {
        while (!_stopListen) {
            try {
                if (_socket != null) {
                    String msg = "";
                    if ((msg = _bf.readLine()) != null && msg.length() > 0) {
                        messageHandlerInterface.HandleMessage(msg);
                    }
                    int a = 0;
                }
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(SocketReceiver.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                if (!_stopListen) {
                    messageHandlerInterface.LostSocket();
                }
                Logger.getLogger(SocketReceiver.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
